//
//  GroupMemberDetailVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/6/2.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "GroupMemberDetailVC.h"
#import "MicroDef.h"
#import "SettingNormalCell.h"
#import "SettingUserInfoCell.h"
#import "ModifyTelephoneVC.h"
#import "ModifyAddressVC.h"
#import "UIActionSheet+Blocks.h"
#import "RIButtonItem.h"
#import "CContactModel.h"
#import <MessageUI/MessageUI.h>
#import "CHChatRoomBase.h"
#import "CXmppRequestMgr.h"
#import "CContactMgr.h"
#import "UIImageView+WebCache.h"
#import "JKAlertDialog.h"
#import "CRecentlyContactMgr.h"
#import "CRecentlyContactModel.h"
#import "MBProgressHUD+WZ.h"
#import "EmailDedailVC.h"
#import "CFolderMgr.h"
#import "CServerSettingModel.h"
#import "CCompanyMgr.h"
#import "CCompany.h"
#import "ChatBase.h"
//#import <AddressBook/AddressBook.h>
//#import <AddressBookUI/AddressBookUI.h>
#import "MBProgressHUD+WZ.h"
#import "WZNavigationController.h"
#import "UIBarButtonItem+category.h"
#import "CMineAttentionContact.h"
#import "CAttentionMgr.h"
#import "EFengPersonalShareController.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#define KSECTIONHEIGHT 35.0f
#define KHEADERCELLHEIGHT 75.0f
#define KNORMALCELLHEIGHT 60.0f
@interface GroupMemberDetailVC ()<UITableViewDelegate, UITableViewDataSource,UIActionSheetDelegate,MFMessageComposeViewControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    UITableView *_tableView;
    UIScrollView *_scrollView;
}

@property (nonatomic, weak) UILabel *autographLabel;
@property (nonatomic, weak) UILabel *nameLabel;
@property (nonatomic, weak) UIButton *jobAndSexButton;
@property (nonatomic ,weak) UIButton *sendButton;
@property (nonatomic, weak) UIImageView *headerImageView;
@property (nonatomic, weak) UIView *headerView;
StrongProperty CRecentlyContactMgr *recentlyMgr;
StrongProperty CAttentionMgr *attentionMgr;
StrongProperty CContactMgr *conMgr;

@end

@implementation GroupMemberDetailVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoDetails) name:K_XMPPGETUSETINFO object:nil];
//
    self.conMgr = [[CContactMgr alloc] init];
    self.recentlyMgr = [[CRecentlyContactMgr alloc] init];
    self.attentionMgr = [[CAttentionMgr alloc] init];
    
    self.member = [self.conMgr loadContactWithUserId:self.member.UserID];
    CCompany *company = [[[CCompanyMgr alloc] init] loadCompanyWithcompCode:self.member.compCode];
    self.member.companyTelePhone = company.callcenterTelephone;
    [self.conMgr updateContact:self.member];
    
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];

    [self.navigationItem setTitle:@"个人资料"];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"icon-more" title:nil target:self sel:@selector(addOftenContact) titleFont:Font10 titleColor:WhiteColor];
    
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (UIView *sub in list) {
            for (UIView *sub1 in sub.subviews) {
                if (sub1.height < 1.0f) {
                    sub1.hidden = YES;
                }
            }
        }
    }

    _scrollView = [[UIScrollView alloc] init];
    _scrollView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.scrollEnabled = YES;
    [self.view addSubview:_scrollView];
    
    UIView *scrollHeaderView = [[UIView alloc] init];
    scrollHeaderView.frame = CGRectMake(0, - HARDWARE_SCREEN_HEIGHT, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT);
    scrollHeaderView.backgroundColor = RGBCOLOR(0x2c, 0xaa, 0xfe);
    [_scrollView addSubview:scrollHeaderView];
    
    
    _tableView = [[UITableView alloc] init];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled = NO;
    [_scrollView addSubview:_tableView];
    
    UIView *headerView = [[UIView alloc] init];
    [headerView setBackgroundColor:RGBCOLOR(0x2c, 0xaa, 0xfe)];
    [_scrollView addSubview:headerView];
    self.headerView = headerView;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showBigPic:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.headerView addGestureRecognizer:tap];
    UIImageView *headerImageView = [[UIImageView alloc] init];
    [headerImageView sd_setImageWithURL:[NSURL URLWithString:[[CXmppRequestMgr shareInstance] DownHeadFileWithContact:self.member.UserID] ] placeholderImage:[UIImage imageNamed:@"testHeader"]];
    headerImageView.layer.cornerRadius = 10.0f/2;
    headerImageView.layer.masksToBounds = YES;
    [headerView addSubview:headerImageView];
    headerImageView.userInteractionEnabled=YES;
    self.headerImageView = headerImageView;
    
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = self.member.UserName;
    [nameLabel setTextAlignment:NSTextAlignmentCenter];
    [nameLabel setTextColor:RGBCOLOR(0xff, 0xff, 0xff)];
    [nameLabel setFont:Font18];
    [headerView addSubview:nameLabel];
    self.nameLabel = nameLabel;
    
    UILabel *autographLabel = [[UILabel alloc] init];
    autographLabel.text = self.member.Autograph;
    self.autographLabel = autographLabel;
    
  
    autographLabel.numberOfLines = 2;
    [autographLabel setTextAlignment:NSTextAlignmentCenter];
    [autographLabel setTextColor:RGBCOLOR(0xff, 0xff, 0xff)];
    [autographLabel setFont:Font15];
    [headerView addSubview:autographLabel];
    
    UIButton *job = [[UIButton alloc] init];
//    job.text = self.member.Position;
    self.jobAndSexButton = job;
    job.titleEdgeInsets = UIEdgeInsetsMake(0, 8.0, 0, 0);
    [job setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    job.userInteractionEnabled = NO;
    job.titleLabel.font = Font15;
    [headerView addSubview:job];
   [self.jobAndSexButton setTitle:self.member.Position forState:UIControlStateNormal];
    
    if ([self.member.SEX isEqualToString:@"女"]) {
        
        [job  setImage:[UIImage imageNamed:@"womanIcon"] forState:UIControlStateNormal];
    } else {
         [job  setImage:[UIImage imageNamed:@"manIcon"] forState:UIControlStateNormal];
    }

    
    
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"发消息" forState:UIControlStateNormal];
    [button setTitleColor:RGBCOLOR(0xff, 0xff, 0xff) forState:UIControlStateNormal];
    [button setBackgroundColor:RGBCOLOR(0x14, 0xc6, 0x4a)];
    button.layer.cornerRadius = 2.5f;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(beginChat) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:button];
    self.sendButton = button;
    
    
//    if (self.member.isDel == NO) {
//        button.hidden = YES;
//    } else {
//        button.hidden = NO;
//    }
    
    
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
}

- (void)getUserInfoDetails
{
    CContactModel *contact = [[[CContactMgr alloc] init] loadContactWithUserCode:self.member.UserCode];
    self.member = contact;
    self.nameLabel.text = self.member.UserName;
    self.autographLabel.text = self.member.Autograph;
    [self.jobAndSexButton setTitle:self.member.Position forState:UIControlStateNormal];
    [_tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _scrollView.frame = self.view.bounds;
    self.headerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 305.0f-64.0f);
    self.headerImageView.frame = CGRectMake((self.view.frame.size.width - 100) / 2.0f , 16.0f, 100, 100);
    self.nameLabel.frame = CGRectMake((self.view.frame.size.width - 200) / 2.0f, 390.0f/2-64.0f, 200, 30);
    self.autographLabel.frame = CGRectMake((self.view.frame.size.width - 210) / 2.0f , 510.0f/2-64.0f, 210, 50);
    self.jobAndSexButton.frame = CGRectMake((self.view.frame.size.width - 300) / 2.0f, 444/2.0f-64.0f, 300, 30);
    _tableView.frame = CGRectMake(0, CGRectGetMaxY(self.headerView.frame), self.view.frame.size.width, 180.0f);
    self.sendButton.frame = CGRectMake(10.0f, CGRectGetMaxY(_tableView.frame) + 20.0f, self.view.frame.size.width - 20, 40);
    
}
//点击查看大图
-(void)showBigPic:(id)sender
{
    MJPhotoBrowser *photoBrower = [[MJPhotoBrowser alloc] init];
    MJPhoto *photo = [[MJPhoto alloc]init];
    photo.image = self.headerImageView.image;
    photoBrower.photos = @[photo];
    [photoBrower show];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
     _scrollView.contentSize = CGSizeMake(HARDWARE_SCREEN_WIDTH, CGRectGetMaxY(self.sendButton.frame) + 20);
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (void)addOftenContact
{
    
    CRecentlyContactModel *model = [self.recentlyMgr loadRecentlyContactWithUserId:self.member.UserID];
    CMineAttentionContact *attention = [self.attentionMgr loadAttentionContactWithUserId:self.member.UserID isAttentionMe:NO];
    
    
    if (model == nil && attention) {
        
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"取消关注",@"查看分享",@"添加常用联系人",@"添加至手机通讯录", nil];
        sheet.tag = 100001;
        [sheet showInView:self.view];
    } else if (model && attention){
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"取消关注",@"查看分享",@"移除常用联系人",@"添加至手机通讯录", nil];
        sheet.tag = 100002;
        [sheet showInView:self.view];


    }   else if (model == nil && attention == nil) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"加为关注",@"查看分享",@"添加常用联系人",@"添加至手机通讯录", nil];
        sheet.tag = 100003;
        [sheet showInView:self.view];

    } else {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"加为关注",@"查看分享",@"移除常用联系人",@"添加至手机通讯录", nil];
        sheet.tag = 100004;
        [sheet showInView:self.view];

    }
   
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPGETUSETINFO object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger rows = 0;
    
    switch (section) {
        case 0:
            rows = 3;
            break;
        case 1:
            rows = 1;
            break;
        default:
            rows = 0;
            break;
    }
    return rows;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 2;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *NormalCellIdentifier = @"SettingNormalCell";
    UITableViewCell *cell = nil;
    
    SettingNormalCell *normalCell = [tableView dequeueReusableCellWithIdentifier:NormalCellIdentifier];
    if (normalCell == nil) {
        normalCell = [[[NSBundle mainBundle] loadNibNamed:@"SettingNormalCell" owner:self options:nil] objectAtIndex:0];
    }
    
    [normalCell.icon setImage:[UIImage imageNamed:[self iconName:indexPath]] forState:UIControlStateNormal];
    [normalCell.titleLabel setText:[self titleName:indexPath]];
    if((indexPath.section == 1 && indexPath.row == 0)
       || (indexPath.section == 0 && indexPath.row == 2) )
    {
        [normalCell.seperatorLine setHidden:YES];
    }
    else
    {
        [normalCell.seperatorLine setHidden:NO];
    }
    
    if((indexPath.section == 0 && indexPath.row == 2) || indexPath.section == 1)
    {
        [normalCell.rightArrow setHidden:NO];
        normalCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell = normalCell;
    
    return cell;
}

-(NSString *)titleName:(NSIndexPath *)indexPath
{
    NSString *title = nil;
    
    switch (indexPath.section) {
        case 0:
        {
                switch (indexPath.row) {
                case 0:
                        if ([self.member.yuLiuZiduan3 isEqualToString:@"isWaibu"]) {
                            if (self.member.companyTelePhone.length<=0) {
                                title = self.member.Telephone;
                            }
                            else
                            {
                                if (self.member.EXtenSion.length > 0) {
                                    title = [NSString stringWithFormat:@"%@-%@",self.member.companyTelePhone,self.member.EXtenSion];
                                } else {
                                    title = self.member.companyTelePhone;
                                }

                            }
                        }
                        else
                        {
                    if (self.member.companyTelePhone.length <= 0 ) {
                        title = self.member.EXtenSion;
                    } else {
                        if (self.member.EXtenSion.length > 0) {
                            title = [NSString stringWithFormat:@"%@-%@",self.member.companyTelePhone,self.member.EXtenSion];
                        } else {
                            title = self.member.companyTelePhone;
                        }
                    }
                    }
                    break;
                case 1:
                    title = self.member.MobileTelephone;
                    break;
                case 2:
                    title = self.member.Email;
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            title = self.deptName;
        }
            break;
        default:
            break;
    }
    return title;
}

-(NSString *)iconName:(NSIndexPath *)indexPath
{
    NSString *iconName = nil;
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    iconName = @"telephoneIcon";
                    break;
                case 1:
                    iconName = @"mobileTelephoneIcon";
                    break;
                case 2:
                    iconName = @"emailIcon";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            iconName = @"partIcon";
        }
            break;
        default:
            break;
    }
    return iconName;
}



#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    CGFloat height = 0;
    switch (section) {
        case 1:
            height = KSECTIONHEIGHT;
            break;
        default:
            break;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
    switch (section) {
        case 1:
            height = 2;
            break;
        default:
            break;
    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section != 1)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = KNORMALCELLHEIGHT;
    
    if(indexPath.row == 0 && indexPath.section == 0)
    {
        height = KNORMALCELLHEIGHT;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    [self showModifyTelVC];
                }
                    break;
                case 1:
                {
                    [self showMobileTelVC];
                }
                    break;
                case 2:
                {
                    [self showModifyEmailVC];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
//            [self showModifyAddressVC];
        }
            break;
        default:
            break;
    }
    
    
}


-(void)showModifyTelVC
{
    //    ModifyTelephoneVC
//    ModifyTelephoneVC *modifyTel = [[ModifyTelephoneVC alloc] init];
//    modifyTel.title = @"修改座机号码";
//    CHSNavigationController *modifyTelNav = [[CHSNavigationController alloc] initWithRootViewController:modifyTel];
//    [self.navigationController pushViewController:modifyTel animated:YES];
    //    [self.leveyTabBarController setHidesBottomBarWhenPushed:YES];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://010-85891937,125"]];
//    @"telprompt://%@",@"186xxxx6979"
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@",@"01085891937,125"]]];
    UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拨打电话", nil];
    alert.tag = 1001;
    [alert showInView:self.view];

}

-(void)showMobileTelVC
{
//    ModifyTelephoneVC *modifyTel = [[ModifyTelephoneVC alloc] init];
//    modifyTel.title = @"修改手机号码";
//    CHSNavigationController *modifyTelNav = [[CHSNavigationController alloc] initWithRootViewController:modifyTel];
//    [self.navigationController pushViewController:modifyTel animated:YES];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://15311435757"]];
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@",@"13717674044"]]];
    
    UIActionSheet *alert = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拨打电话",@"发送短信", nil];
    alert.tag = 1002;
    [alert showInView:self.view];
   
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet.tag == 1002) {
        
        switch (buttonIndex) {
            case 0:
            {
                NSString *phoneStr = [NSString stringWithFormat:@"tel:%@",self.member.MobileTelephone];
                UIWebView *callWebView = [[UIWebView alloc] init];
                [callWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:phoneStr]]];
                [self.view addSubview:callWebView];
                
            }
                break;
            case 1:
            {
                
                // 判断用户设备能否发送短信
                if (![MFMessageComposeViewController canSendText]) {
                    return;
                }
                
                // 1. 实例化一个控制器
                MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
                
                // 2. 设置短信内容
                // 1) 收件人
                controller.recipients = @[self.member.MobileTelephone];
                
                // 2) 短信内容
                //            controller.body = @"给您拜个晚年，祝您晚年快乐！";
                
                // 3) 设置代理
                controller.messageComposeDelegate = self;
                
                // 3. 显示短信控制器
                [self presentViewController:controller animated:YES completion:nil];
                
            }
                break;
            case 2:
            {
                
            }
                break;
                
            default:
                break;
        }
    } else if (actionSheet.tag == 1001) {
        switch (buttonIndex) {
            case 0:
            {
                NSString *phoneStr;
                
                if (self.member.EXtenSion.length > 0) {
                    phoneStr = [NSString stringWithFormat:@"tel:%@,%@",[self.member.companyTelePhone stringByReplacingOccurrencesOfString:@"-" withString:@""],self.member.EXtenSion];
                } else {
                    phoneStr = [NSString stringWithFormat:@"tel:%@",[self.member.companyTelePhone stringByReplacingOccurrencesOfString:@"-" withString:@""]];
                }
                
                UIWebView *callWebView = [[UIWebView alloc] init];
                [callWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:phoneStr]]];
                [self.view addSubview:callWebView];
                
            }
                break;
                default:
                break;
        }

    } else {
        
        
        switch (buttonIndex) {
            case 0:
            {
                __block CMineAttentionContact *attention = [self.attentionMgr loadAttentionContactWithUserId:self.member.UserID isAttentionMe:NO];
                if (attention) {
                    [[CXmppRequestMgr shareInstance] cancelMineAttentionWithUserId:attention.userId successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                        
                        NSString *result = responseObject[@"result"];
                        if ([result isEqualToString:@"success"]) {
                            [MBProgressHUD showSuccess:@"已取消关注" toView:self.view];
                            [self.attentionMgr delAttentionContact:attention.userId];
                            [[NSNotificationCenter defaultCenter] postNotificationName:IMDIDUPDATEMINEATTENTION object:nil];
                        } else {
                            [MBProgressHUD showError:@"取消关注失败" toView:self.view];
                        }

                        
                    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [MBProgressHUD showError:@"取消关注失败" toView:self.view];
                    }];
                } else {
                    attention = [[CMineAttentionContact alloc] init];
                    attention.userId = self.member.UserID;
                    [[CXmppRequestMgr shareInstance] addMineAttentionWithUserId:self.member.UserID successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
                        NSString *result = responseObject[@"result"];
                        
                        if ([result isEqualToString:@"success"]) {
                            [MBProgressHUD showSuccess:@"已关注" toView:self.view];
                            [self.attentionMgr insertAttentionContact:attention];
                            [[NSNotificationCenter defaultCenter] postNotificationName:IMDIDUPDATEMINEATTENTION object:nil];
                        } else {
                            [MBProgressHUD showError:@"添加关注失败" toView:self.view];
                        }

                    } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
                        [MBProgressHUD showError:@"添加关注失败" toView:self.view];
                    }];
                }
            }
                break;
            case 1:
            {
                EFengPersonalShareController *per = [[EFengPersonalShareController alloc] init];
                per.userId = self.member.UserID;
                [self.navigationController pushViewController:per animated:YES];
            }
                break;
            case 2:
            {
                CRecentlyContactModel *model = [self.recentlyMgr loadRecentlyContactWithUserId:self.member.UserID];
                if (model) {
                    [[[CRecentlyContactMgr alloc] init] delRecentlyContact:self.member.UserID];
                    if (![[CXmppMgr shareInstance].xmppStream isDisconnected]) {
                        [[CXmppRequestMgr shareInstance] delOftenContactWithUserId:self.member.UserID];
                        [MBProgressHUD showSuccess:@"删除成功!"];
                    } else {
                        [MBProgressHUD showError:@"保存失败，请您检查网络"];
                    }

                } else {
                    model = [[CRecentlyContactModel alloc] init];
                    model.userId = self.member.UserID;
                    [[[CRecentlyContactMgr alloc] init] insertRecentlyContact:model];
                    if (![[CXmppMgr shareInstance].xmppStream isDisconnected]) {
                        [[CXmppRequestMgr shareInstance] addOftenContactWithUserId:self.member.UserID];
                        [MBProgressHUD showSuccess:@"添加成功!"];
                    } else {
                        [MBProgressHUD showError:@"保存失败，请您检查网络"];
                    }

                }

            }
                break;
                case 3:
            {
//                [self membDetailSavePhone];
                [self saveMemberDetail];
            }
                break;
            default:
                break;
        }
    }
}
#pragma mark 保存联系人号码
-(void)saveMemberDetail
{
    NSString *worknumber = nil;
    if (self.member.companyTelePhone.length <= 0 ) {
        worknumber = self.member.EXtenSion;
    } else {
        if (self.member.EXtenSion.length > 0) {
            worknumber = [NSString stringWithFormat:@"%@-%@",self.member.companyTelePhone,self.member.EXtenSion];
        } else {
            worknumber = self.member.companyTelePhone;
        }
    }

    CNMutableContact *contact = [[CNMutableContact alloc]init];
    contact.givenName = self.member.UserName;
    CNLabeledValue *workEmail = [CNLabeledValue labeledValueWithLabel:CNLabelWork value:self.member.Email];
    contact.emailAddresses = @[workEmail];
    CNLabeledValue *phoneNumber = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMobile value:[CNPhoneNumber phoneNumberWithStringValue:self.member.MobileTelephone]];
    CNLabeledValue *workNumber = [CNLabeledValue labeledValueWithLabel:CNLabelPhoneNumberMain value:[CNPhoneNumber phoneNumberWithStringValue:worknumber]];
    contact.phoneNumbers = @[phoneNumber,workNumber];
    CNMutablePostalAddress *address = [[CNMutablePostalAddress alloc]init];
    address.street = self.member.address;
    contact.postalAddresses = @[[CNLabeledValue labeledValueWithLabel:CNLabelWork value:address]];
    CNSaveRequest * saveRequest = [[CNSaveRequest alloc]init];
    CNContactStore * store = [[CNContactStore alloc]init];
    
    //检索条件，检索所有名字中有的联系人
    NSPredicate * predicate = [CNContact predicateForContactsMatchingName:self.member.UserName];
    //提取数据
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSError *error;
        NSArray * contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:@[CNContactGivenNameKey] error:nil];
        if (contacts.count == 0) {
            [saveRequest addContact:contact toContainerWithIdentifier:nil];
          [store executeSaveRequest:saveRequest error:&error];
            if (!error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showSuccess:@"保存成功"];

                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"保存失败"];
                    
                });
            }
            
        }
        else
        {
            //bug  9485 fixed by lixu
            CNMutableContact *contact1 = [contacts.firstObject mutableCopy];
            [saveRequest deleteContact:contact1];
            [saveRequest addContact:contact toContainerWithIdentifier:nil];
            [store executeSaveRequest:saveRequest error:&error];
            if (!error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showSuccess:@"更新成功"];
                    
                });

            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"更新失败"];
                    
                });
            }
        }
        

    });
    }
//- (void)membDetailSavePhone
//{
//    CFTypeRef phoneRef = (__bridge CFTypeRef)self.member.MobileTelephone;
//
//    ABUnknownPersonViewController *new=[[ABUnknownPersonViewController alloc]init];
////    new.unknownPersonViewDelegate = self;
//    ABRecordRef record = ABPersonCreate();
//    CFErrorRef error;
//    //    // 设置联系人的名字
//        ABRecordSetValue(record, kABPersonLastNameProperty, (__bridge CFTypeRef)self.member.UserName, &error);
//    // 添加联系人电话号码以及该号码对应的标签名
//    ABMultiValueIdentifier idOut = kABMultiValueInvalidIdentifier;
//    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
//    ABMultiValueAddValueAndLabel(multi, phoneRef, kABPersonPhoneMobileLabel, &idOut);
//    ABRecordSetValue(record, kABPersonPhoneProperty, multi, &error);
//    
//    ABAddressBookRef addressBook = nil;
//    // 如果为iOS6以上系统，需要等待用户确认是否允许访问通讯录。
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
//    {
//        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//        //等待同意后向下执行
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)                                                 {
//            dispatch_semaphore_signal(sema);
//        });
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//    }else{
//        addressBook = ABAddressBookCreate();
//    }
//    // 将新建联系人记录添加如通讯录中
//    
//    
//    new.displayedPerson = record;
//    new.allowsAddingToAddressBook = YES;//允许添加
//    new.addressBook = addressBook;
//    //    new.allowsActions = YES;//默认no，设置为yes可以显示发送消息以及打电话
//    
//    
//    CFRelease(addressBook);
//    CFRelease(record);
//    CFRelease(multi);
//    
//    [self.navigationController pushViewController:new animated:YES];
//    
//}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void)showModifyEmailVC
{
//    跳到邮箱详情页
    EmailDedailVC *emailVc = [[EmailDedailVC alloc] init];
    emailVc.userEmail=self.member.Email;
    [self.navigationController pushViewController:emailVc animated:YES];}

-(void)showModifyAddressVC
{
//    ModifyAddressVC *modifyAddr = [[ModifyAddressVC alloc] init];
//    CHSNavigationController *modifyAddrNav = [[CHSNavigationController alloc] initWithRootViewController:modifyAddr];
//    [self.navigationController pushViewController:modifyAddr animated:YES];
}

#pragma mark 开始聊天
- (void)beginChat
{
    
    CHChatRoomBase *chat = [[CHChatRoomBase alloc] init];
    chat.member = self.member;
    chat.group = nil;

    WZNavigationController *rotNav = (WZNavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *vc = rotNav.childViewControllers[1];
    [rotNav popToViewController:vc animated:NO];
    
    [rotNav pushViewController:chat animated:YES];

}



@end
